import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Modal,
  Spin,
  Button,
  message,
  Card,
  Row,
  Col,
  Radio,
  Form,
  Input,
  DatePicker,
  Select,
  Table,
  Drawer,
  Badge,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { FormattedMessage } from 'umi/locale';
import APP from '@/components/Tool/BaseAPP';
import router from 'umi/router';
import moment from 'moment';

@connect(({ pointModel }) => ({
  pointModel,
}))
@Form.create()
class editPoint extends Component {
  state = {
    loading: false,
    editData: {},
    elevatorEditData: {},
    houseList: null,
    elevatorList: null,
    employeeList: null,
    isShowHouseModal: false,
    isShowElevatorModal: false,
    isShowEmployeeModal: false,
    editDataId: null,
    unbindImeiList: null,
    visible: false,
    placement: 'left',
  };

  componentDidMount() {
    this.initPageParams();
  }

  initPageParams() {
    const { state } = this.props.location;
    if (APP.isValidObj(state)) {
      const { id } = state;
      this.setState({ editDataId: id });
      this.getDataById(id);
    }
  }

  getDataById = id => {
    if (!id || !APP.isValidObj(id)) return;
    const that = this;
    const { dispatch, form } = that.props;
    APP.loading(that);
    dispatch({
      type: 'pointModel/getPointById',
      payload: { id: id },
      callback: function(data) {
        APP.closeLoading(that);
        if (data.success) {
          form.resetFields();
          that.setState({
            editData: data.datas,
          });
        }
      },
    });
  };

  loadUnbindList = () => {
    const that = this;
    const { dispatch, form } = that.props;
    APP.loading(that);
    dispatch({
      type: 'pointModel/loadUnbindList',
      payload: {},
      callback: function(data) {
        APP.closeLoading(that);
        if (data.success) {
          const _unbindImeiList = data.datas;
          console.log(_unbindImeiList);
          form.resetFields();
          that.setState({
            unbindImeiList: _unbindImeiList,
          });
        }
      },
    });
  };

  findHouseDataSource = (e, form) => {
    const that = this;
    const { dispatch } = that.props;
    let params = {};
    if (e) e.preventDefault();
    if (form) {
      form.validateFieldsAndScroll((err, values) => {
        APP.validNilParams(values);
        params = { ...params, ...values };
        requestContinue();
      });
    } else requestContinue();
    function requestContinue() {
      APP.loading(that);
      dispatch({
        type: 'pointModel/houseList',
        payload: params,
        callback: function(data) {
          APP.closeLoading(that);
          if (data.success) {
            that.setState({
              houseList: data.datas,
              isShowHouseModal: true,
            });
          }
        },
      });
    }
  };

  findElevatorList = hourseId => {
    const that = this;
    const { dispatch } = that.props;
    const params = {
      notLimit: true,
      hourseId: hourseId,
    };
    APP.loading(that);
    dispatch({
      type: 'elevatorModel/list',
      payload: params,
      callback: function(data) {
        APP.closeLoading(that);
        if (data.success) {
          that.setState({
            elevatorList: data.datas.list,
            isShowElevatorModal: true,
          });
        }
      },
    });
  };

  findEmployeeList = (e, form) => {
    const that = this;
    const { dispatch } = that.props;
    let params = { postId: 1 };
    if (e) e.preventDefault();
    if (form) {
      form.validateFieldsAndScroll((err, values) => {
        APP.validNilParams(values);
        params = { ...params, ...values };
        requestContinue();
      });
    } else requestContinue();
    function requestContinue() {
      APP.loading(that);
      dispatch({
        type: 'pointModel/getEmployeeList',
        payload: params,
        callback: function(data) {
          APP.closeLoading(that);
          if (data.success) {
            that.setState({
              employeeList: data.datas,
              isShowEmployeeModal: true,
            });
          }
        },
      });
    }
  };

  submit = e => {
    e.preventDefault();
    const that = this;
    const { dispatch, form } = that.props;
    form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      APP.validNilParams(values);
      values.installDate = APP.momentFormatToStr(values.installDate);
      values.expireDate = APP.momentFormatToStr(values.expireDate);
      requestContinue(values);
    });
    function requestContinue(params) {
      APP.loading(that);
      dispatch({
        type: 'pointModel/savePoint',
        payload: params,
        callback: function(data) {
          if (data.success) {
            message.success('提交成功');
            router.push({
              pathname: '/point/point',
              state: {},
            });
          } else {
            APP.closeLoading(that);
            message.error(data.msg);
          }
        },
      });
    }
  };

  onClose = () => {
    this.setState({
      visible: false,
    });
  };

  onChange = e => {
    this.setState({
      placement: e.target.value,
    });
  };

  chooseImei = e => {
    console.log('chooseImei...');
    this.loadUnbindList();
    this.setState({
      visible: true,
    });
  };

  setImei = val => {
    console.log(val);
    this.setState({
      editData: {
        imei: val,
      },
    });
    this.onClose();
  };

  render() {
    const { loading, editData, visible, unbindImeiList } = this.state;
    const { form } = this.props;
    const that = this;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      style: {
        margin: '10px',
      },
    };
    let unbindImeiArr = [];
    for (let key in unbindImeiList) {
      unbindImeiArr.push({ imei: key, time: unbindImeiList[key] });
    }
    return (
      <Spin spinning={loading}>
        <PageHeaderWrapper title={<FormattedMessage id="menu.point.editPoint" />}>
          <Card>
            <Form
              onSubmit={this.submit}
              style={{ maxWidth: 900, margin: '0 auto' }}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
            >
              {getFieldDecorator('id', { initialValue: editData.id })(<Input hidden={true} />)}
              {getFieldDecorator('hourseId', { initialValue: editData.hourseId })(
                <Input hidden={true} />,
              )}
              {getFieldDecorator('elevatorId', { initialValue: editData.elevatorId })(
                <Input hidden={true} />,
              )}
              {getFieldDecorator('worker', { initialValue: editData.worker })(
                <Input hidden={true} />,
              )}
              <Row>
                <Col span={12}>
                  <Form.Item label="所属楼盘" {...formItemLayout}>
                    {getFieldDecorator('hourseName', {
                      initialValue: editData.hourseName,
                      rules: [
                        {
                          required: true,
                          message: '请选择楼盘！',
                        },
                      ],
                    })(
                      <Input
                        placeholder="请选择楼盘"
                        readOnly={true}
                        style={{ cursor: 'pointer' }}
                        onClick={() => {
                          const { houseList } = this.state;
                          if (!houseList) this.findHouseDataSource();
                          else this.setState({ isShowHouseModal: true });
                        }}
                      />,
                    )}
                  </Form.Item>
                </Col>
                <Col span={12} style={{ float: 'right' }}>
                  <Form.Item label="所属电梯" {...formItemLayout}>
                    {getFieldDecorator('elevatorName', {
                      initialValue: editData.elevatorName,
                      rules: [
                        {
                          required: true,
                          message: '请选择所属电梯！',
                        },
                      ],
                    })(
                      <Input
                        placeholder="请选择所属电梯"
                        readOnly={true}
                        style={{ cursor: 'pointer' }}
                        onClick={() => {
                          const { elevatorList } = this.state;
                          if (!elevatorList) {
                            const hourseId = form.getFieldValue('hourseId');
                            if (hourseId) {
                              this.findElevatorList(hourseId);
                            } else {
                              message.error('请选择楼盘！');
                            }
                          } else this.setState({ isShowElevatorModal: true });
                        }}
                      />,
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <Form.Item label="设备生产商" {...formItemLayout}>
                    {getFieldDecorator('producer', {
                      initialValue: editData.producer,
                      rules: [
                        {
                          required: true,
                          message: '请输入设备生产商！',
                        },
                      ],
                    })(<Input placeholder={'请输入设备生产商'} />)}
                  </Form.Item>
                </Col>
                <Col span={12} style={{ float: 'right' }}>
                  <Row gutter={8}>
                    <Col span={20}>
                      <Form.Item label="机器串码" {...formItemLayout}>
                        {getFieldDecorator('imei', {
                          initialValue: editData.imei,
                          rules: [
                            {
                              required: true,
                              message: '请输入机器串码！',
                            },
                          ],
                        })(<Input placeholder={'请输入机器串码'} />)}
                      </Form.Item>
                    </Col>
                    <Col span={4} style={{ marginTop: 20 }}>
                      <a onClick={this.chooseImei}>选择串码</a>
                    </Col>
                  </Row>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <Form.Item label="安装师傅" {...formItemLayout}>
                    {getFieldDecorator('workerName', {
                      initialValue: editData.workerName,
                      rules: [
                        {
                          required: true,
                          message: '请选择安装师傅！',
                        },
                      ],
                    })(
                      <Input
                        placeholder={'请选择安装师傅'}
                        readOnly={true}
                        style={{ cursor: 'pointer' }}
                        onClick={() => {
                          const { employeeList } = this.state;
                          if (!employeeList) this.findEmployeeList();
                          else this.setState({ isShowEmployeeModal: true });
                        }}
                      />,
                    )}
                  </Form.Item>
                </Col>
                <Col span={12} style={{ float: 'right' }}>
                  <Form.Item label="安装日期" {...formItemLayout}>
                    {getFieldDecorator('installDate', {
                      initialValue: (function() {
                        const { installDate } = editData;
                        if (installDate) {
                          return moment(installDate, 'YYYY-MM-DD');
                        }
                      })(),
                      rules: [
                        {
                          required: true,
                          message: '请选择安装日期！',
                        },
                      ],
                    })(
                      <DatePicker
                        placeholder="请选择安装日期"
                        style={{
                          width: '100%',
                        }}
                      />,
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <Form.Item
                    label="备注"
                    {...formItemLayout}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                  >
                    {getFieldDecorator('remark', {
                      initialValue: editData.remark,
                    })(
                      <Input.TextArea
                        placeholder="请输入备注"
                        className="custom"
                        style={{ height: 150 }}
                      />,
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col
                  style={{ textAlign: 'center', height: '32px', lineHeight: '32px', marginTop: 20 }}
                >
                  <Button type="primary" htmlType="submit" {...APP.buttonsStyle_MR15}>
                    提交
                  </Button>
                  <Button
                    type="primary"
                    onClick={() => {
                      form.resetFields();
                    }}
                  >
                    重置
                  </Button>
                </Col>
              </Row>
            </Form>
          </Card>
          <HouseModal parent={this}/>
          <ElevatorModal parent={this}/>
          <EmployeeModal parent={this} />
          <Drawer
            title="未绑定机器串码"
            placement="right"
            closable={false}
            onClose={this.onClose}
            visible={visible}
            width={380}
            key="right"
          >
            {unbindImeiArr.map((item, idx) => {
              return (
                <>
                  <Row>
                    <Col span={24}>
                      <a
                        onClick={() => {
                          that.setImei(item.imei);
                        }}
                      >
                        {item.imei}
                        <span style={{ color: 'blue' }}>[{item.time}]</span>
                      </a>
                    </Col>
                  </Row>
                </>
              );
            })}
          </Drawer>
        </PageHeaderWrapper>
      </Spin>
    );
  }
}

/**
 * 所属楼盘选择窗口
 * @Author 肖家添
 * @Date 2020/3/17 23:07
 */
const HouseModal = Form.create()(props => {
  const { parent, form } = props;
  const { dispatch } = parent.props;
  const { loading, isShowHouseModal, editData, houseList } = parent.state;
  const { getFieldDecorator } = form;
  const formItemLayout = {
    style: {
      margin: '0px',
    },
  };
  //-- 提交
  function submit(e) {
    parent.findHouseDataSource(e, form);
  }
  //-- 显示/隐藏 数据编辑窗口
  function handlerEditModal() {
    form.resetFields();
    let { isShowHouseModal } = parent.state;
    isShowHouseModal = !isShowHouseModal;
    parent.setState({ isShowHouseModal });
  }
  if (!houseList) return <div></div>;
  return (
    <Modal
      visible={isShowHouseModal}
      width={800}
      confirmLoading={loading}
      footer={false}
      onCancel={() => handlerEditModal()}
    >
      <Spin spinning={loading}>
        <Form onSubmit={submit} layout={'inline'} style={{ marginBottom: 20 }}>
          <Form.Item label="楼盘名称" {...formItemLayout} {...APP.buttonsStyle_MR15}>
            {getFieldDecorator('houseName', {
              rules: [{ required: false, message: '请输入楼盘名称！' }],
              initialValue: editData.houseName,
            })(<Input placeholder="请输入楼盘名称" />)}
          </Form.Item>
          <Form.Item>
            <Button type={'primary'} htmlType="submit" {...APP.buttonsStyle_MR15}>
              查询
            </Button>
          </Form.Item>
        </Form>
        <Table
          bordered
          rowKey={data => `${data.id}`}
          columns={[
            { title: '楼盘名称', dataIndex: 'houseName', key: 'houseName' },
            { title: '楼盘类型', dataIndex: 'gvlistName', key: 'gvlistName' },
            { title: '楼盘位置', dataIndex: 'areaName', key: 'areaName' },
          ]}
          dataSource={houseList}
          onRow={record => {
            return {
              onClick: event => {
                const { form } = parent.props;
                form.setFieldsValue({
                  hourseId: record.id,
                  hourseName: record.houseName,
                  elevatorId: null,
                  elevatorName: null,
                });
                parent.setState({ elevatorList: null });
                handlerEditModal();
              },
            };
          }}
          pagination={{
              showTotal: total => `共 ${total} 条数据`,
          }}
        />
      </Spin>
    </Modal>
  );
});

/**
 * 电梯信息编辑窗口
 * @Author 肖家添
 * @Date 2020/3/17 23:07
 */
const ElevatorModal = Form.create()(props => {
  const { parent, form } = props;
  const { dispatch } = parent.props;
  const { loading, isShowElevatorModal, elevatorEditData, elevatorList } = parent.state;
  const { getFieldDecorator } = form;
  const editData = elevatorEditData;
  editData.hourseId = parent.props.form.getFieldValue('hourseId');
  const formItemLayout = {
    style: {
      margin: '0px',
    },
  };
  //-- 提交
  function submit(e) {
    if (e) e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      APP.validNilParams(values);
      requestContinue(values);
    });
    function requestContinue(values) {
      APP.loading(parent);
      dispatch({
        type: 'pointModel/saveElevator',
        payload: values,
        callback: function(data) {
          APP.closeLoading(parent);
          if (data.success) {
            message.success('提交成功');
            parent.findElevatorList(values.hourseId);
          } else {
            message.error(data.msg);
          }
        },
      });
    }
  }
  //-- 显示/隐藏 数据编辑窗口
  function handlerEditModal() {
    form.resetFields();
    let { isShowElevatorModal } = parent.state;
    isShowElevatorModal = !isShowElevatorModal;
    parent.setState({ isShowElevatorModal });
  }
  return (
    <Modal
      visible={isShowElevatorModal}
      width={1000}
      confirmLoading={loading}
      footer={false}
      closable={false}
      onCancel={() => handlerEditModal()}
    >
      <Spin spinning={loading}>
        <Card style={{ marginBottom: 15 }}>
          <Form
            onSubmit={submit}
            style={{ maxWidth: 600, margin: '0 auto' }}
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
          >
            {getFieldDecorator('id', { initialValue: editData.id })(<Input hidden={true} />)}
            {getFieldDecorator('hourseId', { initialValue: editData.hourseId })(
              <Input hidden={true} />,
            )}
            <Row>
              <Col span={12}>
                <Form.Item label="所在楼栋" {...formItemLayout}>
                  {getFieldDecorator('sbuild', {
                    rules: [{ required: true, message: '请输入所在楼栋！' }],
                    initialValue: editData.sbuild,
                  })(<Input placeholder="请输入所在楼栋" />)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="所在单元" {...formItemLayout}>
                  {getFieldDecorator('iunint', {
                    rules: [{ required: true, message: '请输入所在单元！' }],
                    initialValue: editData.iunint,
                  })(<Input placeholder="请输入所在单元" />)}
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="电梯名称" {...formItemLayout}>
                  {getFieldDecorator('ename', {
                    rules: [{ required: true, message: '请输入电梯名称！' }],
                    initialValue: editData.ename,
                  })(<Input placeholder="请输入电梯名称" />)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="电梯品牌" {...formItemLayout}>
                  {getFieldDecorator('brand', {
                    rules: [{ required: true, message: '请输入电梯品牌！' }],
                    initialValue: editData.brand,
                  })(<Input placeholder="请输入电梯品牌" />)}
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Form.Item
                label="电梯备注"
                {...formItemLayout}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
              >
                {getFieldDecorator('remark', {
                  initialValue: editData.remark,
                })(
                  <Input.TextArea
                    placeholder="请输入备注"
                    className="custom"
                    style={{ height: 150, width: '100%' }}
                  />,
                )}
              </Form.Item>
            </Row>
            <div style={{ textAlign: 'center', marginTop: 25 }}>
              <Button type={'primary'} htmlType="submit" {...APP.buttonsStyle_MR15}>
                保存
              </Button>
            </div>
          </Form>
        </Card>
        <Table
          bordered
          rowKey={data => `${data.id}`}
          columns={[
            { title: '所在楼栋', dataIndex: 'sbuild', key: 'sbuild' },
            { title: '所在单元', dataIndex: 'iunint', key: 'iunint' },
            { title: '电梯名称', dataIndex: 'ename', key: 'ename' },
            { title: '电梯品牌', dataIndex: 'brand', key: 'brand' },
            { title: '备注', dataIndex: 'remark', key: 'remark' },
            {
              title: '操作',
              width: 65,
              render: (text, record) => {
                return (
                  <div>
                    <a
                      onClick={e => {
                        form.resetFields();
                        parent.setState({ elevatorEditData: record });
                        e.stopPropagation();
                      }}
                    >
                      编辑
                    </a>
                  </div>
                );
              },
            },
          ]}
          dataSource={elevatorList}
          onRow={record => {
            return {
              onClick: event => {
                const { form } = parent.props;
                const { ename, sbuild, iunint } = record;
                form.setFieldsValue({
                  elevatorId: record.id,
                  elevatorName: `${sbuild + '-' + iunint + '-' + ename}`,
                });
                handlerEditModal();
              },
            };
          }}
          pagination={{
              showTotal: total => `共 ${total} 条数据`,
          }}
        />
      </Spin>
    </Modal>
  );
});

/**
 * 员工选择窗口
 * @Author 肖家添
 * @Date 2020/3/18 0:34
 */
const EmployeeModal = Form.create()(props => {
  const { parent, form } = props;
  const { dispatch } = parent.props;
  const { loading, isShowEmployeeModal, editData, employeeList } = parent.state;
  const { getFieldDecorator } = form;
  const formItemLayout = {
    style: {
      margin: '0px',
    },
  };
  //-- 提交
  function submit(e) {
    parent.findEmployeeList(e, form);
  }
  //-- 显示/隐藏 数据编辑窗口
  function handlerEditModal() {
    form.resetFields();
    let { isShowEmployeeModal } = parent.state;
    isShowEmployeeModal = !isShowEmployeeModal;
    parent.setState({ isShowEmployeeModal });
  }
  if (!employeeList) return <div></div>;
  return (
    <Modal
      visible={isShowEmployeeModal}
      width={800}
      confirmLoading={loading}
      footer={false}
      onCancel={() => handlerEditModal()}
    >
      <Spin spinning={loading}>
        <Form onSubmit={submit} layout={'inline'} style={{ marginBottom: 20 }}>
          <Form.Item label="员工姓名" {...formItemLayout} {...APP.buttonsStyle_MR15}>
            {getFieldDecorator('name', {
              rules: [{ required: false, message: '请输入员工姓名！' }],
              initialValue: editData.name,
            })(<Input placeholder="请输入员工姓名" />)}
          </Form.Item>
          <Form.Item>
            <Button type={'primary'} htmlType="submit" {...APP.buttonsStyle_MR15}>
              查询
            </Button>
          </Form.Item>
        </Form>
        <Table
          bordered
          rowKey={data => `${data.id}`}
          columns={[
            { title: '员工姓名', dataIndex: 'name', key: 'name' },
            { title: '手机号', dataIndex: 'phone', key: 'phone' },
            {
              title: '员工状态',
              dataIndex: 'xstatus',
              key: 'xstatus',
              render: text => {
                if (text === 1) return '已入职';
                else if (text === 2) return '离职';
                else if (text === 3) return '休假';
                else return '其他';
              },
            },
          ]}
          dataSource={employeeList}
          onRow={record => {
            return {
              onClick: event => {
                const { form } = parent.props;
                form.setFieldsValue({
                  worker: record.id,
                  workerName: record.name,
                });
                handlerEditModal();
              },
            };
          }}
          pagination={{
              showTotal: total => `共 ${total} 条数据`,
          }}
        />
      </Spin>
    </Modal>
  );
});

export default editPoint;
